﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Caching.Distributed;
using MiniErp.Common.Cache;
using MiniErp.Core.Auth;
using MiniErp.Entity.DataStreams.BOs;
using MiniErp.Entity.JWTs;
using MiniErp.Service.BusinessService.IService;

namespace MiniErp.Core.Auth
{
    /// <summary>
    /// 权限处理
    /// </summary>
    public class PermissionHandler : IPermissionHandler
    {
        private readonly IUserService _userService;
        private readonly ICache _cache;
        public PermissionHandler(IUserService userService, ICache cache)
        {
            _userService = userService;
            _cache = cache;
        }

        public async Task<bool> ValidateAsync(string api, string httpMethod, IEnumerable<Claim> claims)
        {
            var uid = claims.FirstOrDefault(item => item.Type == ClaimsModel.UId).Value;
            var jobsid = claims.FirstOrDefault(item => item.Type == ClaimsModel.JobsId).Value;
            //从缓存中获取权限集合
            var permissions = await _cache.GetDataByCacheOrDBAsync(CacheKeyType.Right, uid,
                async () => await _userService.GetUserRightByMysql(Convert.ToInt32(jobsid)));
            //获取权限集合中满足条件的权限信息
            var accessRights = permissions.FirstOrDefault(item => item.SystemsRoute == api);

            return accessRights is null
                ? false
                : httpMethod switch
                {
                    "GET" when accessRights.RightName == "Admin" || accessRights.RightName == "Root" => true,
                    "POST" when accessRights.RightName == "Admin" => true,
                    "DELETE" when accessRights.RightName == "Admin" => true,
                    "PUT" when accessRights.RightName == "Admin" => true,
                    _ => false
                };

        }
    }
}
